package ua.com.alus.resvac.crm.util.converters;

import net.sourceforge.stripes.validation.ScopedLocalizableError;
import net.sourceforge.stripes.validation.TypeConverter;
import net.sourceforge.stripes.validation.ValidationError;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

/**
 * Year2Date converter
 * Created by Usatov Alexey
 */
public class YearToDateConverter implements TypeConverter<Date> {
    private Locale locale;

    @Override
    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    @Override
    public Date convert(String input, Class<? extends Date> targetType, Collection<ValidationError> errors) {
        Date date;
        try {
            int years = Integer.parseInt(input);
            Calendar calendar = Calendar.getInstance(locale);
            calendar.set(Calendar.YEAR, years);
            date = calendar.getTime();
        } catch (NumberFormatException nfe) {
            errors.add(new ScopedLocalizableError("converter.date", "invalidDate"));
            return null;
        }
        return date;
    }
}
